<script lang="ts" setup>
//首页
import LatestNews from "@/components/index/Latest-News.vue";
//import Featured from "@/components/Index/Featured.vue";
import Stories from "@/components/index/Stories.vue";
import MoreNews from "@/components/index/More-News.vue";
import Carousel from "@/components/index/Carousel.vue";

import { ref, reactive, watch, onMounted, watchEffect } from "vue";
import useGetData from "@/store/get";
import { IndexShowData, GetOptionData } from "@/api/interface";
// 实例化 store
const store = useGetData();

//加载数据,返回配置数据和11篇文章的ID
const getList = async (config: GetOptionData) => {
  //第二次请求

  //获取首页11篇文章的ID
  const getIndexId = store.GetLatestData();
  //获取阅读更多的文章ID
  const getMoreId = store.GetCatPostData(config.index.more.category, 6);
  //发出请求
  const [indexId, moreId] = await Promise.all([getIndexId, getMoreId]);

  //第三次请求
  //获取幻灯片ID
  const carouselId = config.index.tone.carousel;

  //将数组合并
  const arr = [...indexId, ...carouselId, ...moreId];

  //去重后的文章ID数组
  const arrSet = [...new Set(arr)];

  //获取所有信息
  const data = await store.packageEasyPostData(arrSet);

  //使用接口获取值
  //const data = await store.GetHandleIdArr(arrSet);
  //发出请求取值

  const obj = {
    list: indexId,
    carousel: carouselId,
    more: moreId,
    obj: data,
    option: config,
  };

  return obj;
};

/**
 * 整理数据
 * 传入数组和处理对象，将对象中的值取出
 * @param arr 待提取数组
 * @param obj 数据源
 */
const handleData = (arr: Array<number>, obj = [{ id: 0 }]) => {
  const data = obj.filter((obj) => {
    if (arr.includes(Number(obj.id))) {
      return obj;
    }
  });

  return data as IndexShowData[];
};

const config = reactive({
  //存储文章数据
  data: {
    list: [] as IndexShowData[],
    carousel: [] as IndexShowData[],
    more: [] as IndexShowData[],
  },
  //配置
  option: {
    carousel: 0,
    more: 0,
  },
});

//直接访问首页
onMounted(() => {
  //获取配置信息
  store.GetOptionData();
  //第一次请求：获取配置信息
});

watchEffect(async () => {
  if (JSON.stringify(store.option) !== "{}") {
    //拿到组件所需信息
    const data = await getList(store.option);

    //组件所需值
    config.data.list = handleData(data.list, data.obj);
    config.data.carousel = handleData(data.carousel, data.obj);
    config.data.more = handleData(data.more, data.obj);
    //按钮所需值
    config.option.carousel = store.option.index.tone.category;
    config.option.more = store.option.index.more.category;
  }
});
</script>

<template>
  <LatestNews :data="config.data.list"></LatestNews>

  <!--幻灯片-->
  <Carousel
    :data="config.data.carousel"
    :link="config.option.carousel"
  ></Carousel>
  <!--
<Featured></Featured>
-->
  <Stories v-if="false"/>
  <MoreNews :data="config.data.more" :link="config.option.more"></MoreNews>
</template>

<style lang="less" scoped></style>
